from django.shortcuts import render
from django.core.cache import cache
from django.core.paginator import Paginator
from goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner
from goods.models import GoodsSKU
from order.models import OrderGoods
from django_redis import get_redis_connection
from django.shortcuts import reverse,redirect


# Create your views here.
def index(request):

    # 判断是否有缓存
    # context = cache.get('index_cache_page')
    context = None
    if context is None:
        # 从数据库中取出首页数据,并设置缓存
        types = GoodsType.objects.all()
        goods_banners = IndexGoodsBanner.objects.all().order_by('index')
        promotion_banners = IndexPromotionBanner.objects.all().order_by('index')

        for type in types:
            image_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
            title_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0)
            goods_sku = GoodsSKU.objects.filter(type=type)[:4]

            type.image_banner = image_banner
            type.title_banner = title_banner
            type.goods_sku = goods_sku
            print(goods_sku)
            print('================')

        context = {'types':types,
                   'goods_banners':goods_banners,
                   'promotion_banners':promotion_banners}


        cache.set('index_cache_page', context, 3600)

    # 获取购物车商品数目
    user = request.user
    cart_count = 0
    if user.is_authenticated:
        conn = get_redis_connection('default')
        cart_key = 'cart_%d'%user.id
        cart_count = conn.hlen(cart_key)
    context.update(cart_count=cart_count)
    print(context)
    return render(request, 'df_goods/index.html', {'context':context})


def ordinary_search(request):
    return render(request, 'df_goods/ordinary_search.html')


def GoodsDetail(request, goods_id):
    '''商品详情页'''
    # detail = cache.get('detail_cache_page')
    detail = None

    # 商品模块内容生成静态页面，有更新时，更新静态页面
    if detail is None:
        try:
            goods_sku = GoodsSKU.objects.get(id=goods_id)
        except:
            message = '商品不存在'
            return redirect(reverse('goods:index'),{'message':message})
        # 新品推荐
        new_goods = GoodsSKU.objects.filter(type=goods_sku.type).order_by('-create_time')[:3]

        # 商品评论
        comment = OrderGoods.objects.filter(sku = goods_sku).exclude(comment='')

        # 同一SPU规格下的其他商品
        # same_spu_skus = GoodsSKU.objects.filter(sku = goods_sku.goods).exclude(id='goods_id')
        goods_detail = goods_sku.goods.detail

        # 分页
        paginator = Paginator(goods_sku, 1)


        detail = {
            'id':goods_sku.id,
            'name':goods_sku.name,
            'desc':goods_sku.desc,
            'unit':goods_sku.unit,
            'stock':goods_sku.stock,
            'sales':goods_sku.sales,
            'image':goods_sku.image,
            'price':goods_sku.price,
            'new_goods':new_goods,
            'comment':comment
        }
        print(goods_detail)
        cache.set('detail_cache_page',detail,3600)

    # 用户历史浏览记录
    user = request.user
    if user.is_authenticated:
        conn = get_redis_connection('default')
        history_key = 'history_%d' % user.id
        conn.lrem(history_key, 0, goods_id)
        conn.lpush(history_key, goods_id)
        # 保留最新的4个
        conn.ltrim(history_key,0,4)
    print(detail)
    return render(request, 'df_goods/detail.html', {'goods':detail,
                                                    'goods_detail':goods_detail,})


def GoodsList(request, type_id, page_id):
    '''商品列表分页'''
    try:
        type = GoodsType.objects.get(id=type_id)
    except:
        # 种类不存在
        redirect(reverse('goods:index'))


    # sort=default
    # sort=price
    # sort=hot
    sort = request.GET.get('sort')

    if sort == 'price':
        skus = GoodsSKU.objects.filter(type=type).order_by('price')
    elif sort == 'hot':
        skus = GoodsSKU.objects.filter(type=type).order_by('sales')
    else:
        sort = 'default'
        skus = GoodsSKU.objects.filter(type=type).order_by('-id')

    paginator = Paginator(skus, 1)
    # 判断页码
    try:
        page = int(page_id)
    except:
        page = 1

    if page > paginator.num_pages:
        page = 1

    skus_page = paginator.page(page)

    # 控制页码只显示5个
    # 1、总页数小于5页，显示所有页码
    # 2、当前页是前3页，显示1 - 5页
    # 3、当前页是后3页，显示后5页
    # 4、其他情况，显示当前页的前2页，和后2页
    num_pages = paginator.num_pages
    if num_pages < 5:
        pages = range(1, num_pages+1)
    elif page <= 3:
        pages = range(1,6)
    elif num_pages - page <=2:
        pages = range(num_pages-4, num_pages-2)
    else:
        pages = range(page-2, page+3)


    context = {
        'page': skus_page,
        'type': type,
        'sort':sort
    }
    print(sort)
    return render(request, 'df_goods/list.html',context)